import datetime

from django.db import models

from sportsground.utils.baseModels import BaseModels, IntegerChoices


class UserVip(BaseModels):
    class Meta():
        db_table = 'user_vip'
        verbose_name = '用户会员卡'
        verbose_name_plural = verbose_name

    class State(IntegerChoices):
        ToUse = 1, "有效"
        Used = 2, "已过期"

    user = models.ForeignKey(to="User", on_delete=models.CASCADE, verbose_name="对应用户")
    vip = models.ForeignKey(to="Venue.Vip", null=True, on_delete=models.CASCADE, verbose_name="会员卡")
    state = models.IntegerField(choices=State.choices, default=State.ToUse, verbose_name="状态")
    value = models.FloatField(verbose_name="剩余价值")
    usedLogs = models.JSONField(default=list, verbose_name="使用记录")

    @classmethod
    def create(cls, user, vip):
        userVip = cls(user=user, vip=vip, state=cls.State.ToUse, value=vip.value)
        userVip.save()

    def Info(self):
        return {
            "id": self.id,
            "state": self.state,
            "vip": self.vip.Info(),
            "getTime": self.createTime,
            "value": self.value,
            "usedLogs": self.usedLogs
        }

    def canUse(self,cost=None):
        """ 检查是否能使用 """
        if self.state != self.State.ToUse:
            return False
        return True

    def income(self, money, msg):
        """ 增加金额 """
        self.value += money
        self.newlog(money, msg)
        self.save()

    def cost(self, money):
        """ 消费会员卡 """
        remain = 0
        derate = 0

        if self.value <= money:
            # 会员卡余额清零
            remain = money - self.value
            self.value = 0
            self.state = self.State.Used
            self.newlog(self.value, "消费")
            derate = self.value
        else:
            self.value -= money
            self.newlog(money, "消费")
            derate = money
        self.save()
        return derate,remain


    def newlog(self,money,message):
        log = {
            "createTime": str(datetime.datetime.now()),
            "cost": money,
            "message": message
        }
        self.usedLogs.insert(0,log)